package com.core.family.admin.controller;

import com.core.family.admin.domain.User;
import com.core.family.admin.domain.req.UserReq;
import com.core.family.admin.service.UserService;
import com.google.code.kaptcha.Producer;
import com.core.common.annotation.MenuDesc;
import com.core.common.cons.RespCode;
import com.core.common.domain.response.R;
import com.core.common.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;


/**
 * @author honglei
 * @version 1.0
 * @time: 2022-3-20 16:34:58
 * @Description 服务实现层 平台用户表
 */
@MenuDesc(desc = "登录登出", code = "user")
@Api(tags = "auth 登录登出")
@RestController
@RequestMapping("/auth/")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    private Producer kaptchaProducer;

    @ApiOperation(value = "admin登录接口")
    @MenuDesc(desc = "登录")
    @PostMapping("login")
    public R get(@RequestBody UserReq userReq) {
     //   {"code":20000,"data":{"token":"admin-token"}}



        if (StringUtils.isEmpty(userReq.getUsername()) && StringUtils.isEmpty(userReq.getMobile())) {
            return R.error(RespCode.resp_error_login);
        }
        User dbUser = userService.selectLimitOne(userReq);
        if (null == dbUser) {
            return R.error(RespCode.resp_error_login);
        }

        if (StringUtils.hasText(userReq.getUsername()) && !dbUser.getUsername().equals(userReq.getUsername())) {
            return R.error(RespCode.resp_error_login);
        }

        if (StringUtils.hasText(userReq.getMobile()) && !dbUser.getUsername().equals(userReq.getMobile())) {
            return R.error(RespCode.resp_error_login);
        }

        String token = JwtUtil.createJwt(dbUser.getId().toString(), dbUser.getMobile(), new HashMap<>());

        //   {"code":20000,"data":{"token":"admin-token"}}
        Map<String, Object> tokenInfo = new HashMap<>();
        tokenInfo.put("token", token);

        return R.ok(tokenInfo);
    }

    @PostMapping("logout")
    public Object logout() {

        return R.ok();
    }


    /**
     * 根据id获取详情
     *
     * @return
     */
    @MenuDesc(desc = "获取详情")
    @GetMapping(value = "info")
    public R getUserInfo(String token) {
        // return R.ok(UserUtil.getUserInfo(token));
        Map<String, Object> data = new HashMap<>();
        data.put("introduction", "I am a super administrator");
        data.put("name", "admin123");
        data.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        roles.add("超级管理员");
        permissions.add("*");

        data.put("roles", roles);
        data.put("perms", permissions);
/*
        {
            "code": 20000,
                "data": {
            "roles": [
            "admin"
        ],
            "introduction": "I am a super administrator",
                    "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
                    "name": "Super Admin"
        }
        }*/

//        "perms":[
//        "GET /admin/brand/list",
//                "POST /admin/category/delete",
//                "GET /admin/category/read",
//                "POST /admin/category/create",
//                "POST /admin/brand/delete",
//                "POST /admin/brand/create",
//                "GET /admin/category/list",
//                "POST /admin/category/update",
//                "GET /admin/brand/read",
//                "POST /admin/brand/update"
//        ],

        //  UserUtil.getUserInfo(token)

        return R.ok(data);
    }

    @GetMapping("kaptcha")
    public Object kaptcha(HttpServletRequest request) {
        String kaptcha = doKaptcha(request);
        if (kaptcha != null) {
            return R.ok(kaptcha);
        }
        return R.error();
    }

    private String doKaptcha(HttpServletRequest request) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        HttpSession session = request.getSession();
        session.setAttribute("kaptcha", text);

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
        } catch (IOException e) {
            return null;
        }
    }


}
